package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MovementsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;


    public String savePublish(String textContent, String location, String longitude, String latitude, MultipartFile[] multipartFile) {
        //校验token
        User user = UserThreadLocal.get();
        //封装数据
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);


        List<String> list = new ArrayList<>();
        //上传图片获取oss地址
        for (MultipartFile file : multipartFile) {
            PicUploadResult upload = picUploadService.upload(file);
            list.add(upload.getName());//将oss地址添加到list
        }
        publish.setMedias(list);
        //调用dubbo保存

        return quanZiApi.savePublish(publish);
    }

    public PageResult queryPublishList(Integer page, Integer pageSize) {
        //获取user
        User user = UserThreadLocal.get();
        return getPageResult(page, pageSize, user);

    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private PageResult getPageResult(Integer page, Integer pageSize, User user) {
        Long userId = null;

        List<Publish> publishes = null;
        //user不为空查好友数据
        if (user != null) {
            userId = user.getId();
            //从dubbo获取时间线表，获取好友发布列表
            publishes = this.quanZiApi.queryPublishList(userId, page, pageSize);
        } else {
            //传递的user为空，查询redis，如果redis有值，用redis里面的，如果没有还是查推荐表
            String rk = "QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId();
            String pidStr = this.redisTemplate.opsForValue().get(rk);
            //如果redisValue有值则进行处理
            if (StringUtils.isNotEmpty(pidStr)) {
                String[] pidStrArray = StringUtils.split(pidStr, ',');
                //根据page和pageSize进行分页，先计算起始索引
                int startIndex = (page - 1) * pageSize;
                //起始索引超出范围能否查询,如果等于是否越界？
                if(startIndex < pidStrArray.length){
                    int endIndex = startIndex + pageSize - 1;
                    if(endIndex >= pidStrArray.length) {
                        //endIndex超过最大长度，要重新设置成最大长度
                        endIndex = pidStrArray.length  - 1;
                    }
                    List<Long> list = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex ; i++) {
                        list.add(Long.valueOf(pidStrArray[i]));
                    }
                    publishes = this.quanZiApi.queryPublishByPids(list);
                }
            }
            //这里如果等于null我们还得查询原先推荐的数据
            if (publishes == null) {
                publishes = this.quanZiApi.queryPublishList(userId, page, pageSize);
            }

        }


        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //判断为空直接返回
        if (CollectionUtils.isEmpty(publishes)) {
            return pageResult;
        }

        //将发布表信息转换成动态展示的数据
        List<Movements> list = getMovements(publishes);
        //list填充到pageResult返回
        pageResult.setItems(list);
        return pageResult;
    }

    private List<Movements> getMovements(List<Publish> publishes) {
        User user;
        user = UserThreadLocal.get();

        Set<Long> userIds = publishes.stream().map(Publish::getUserId).collect(Collectors.toSet());

        //查询userInfo获取头像，昵称，etc
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(UserInfo::getUserId, userIds);

        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(lambdaQueryWrapper);

        List<Movements> list = new ArrayList<>();

        //遍历userInfo，填充数据
        for (Publish publish : publishes) {
            for (UserInfo userInfo : userInfoList) {
                if (publish.getUserId().longValue() == userInfo.getUserId().longValue()) {


                    //从发布表（publish）里面填充数据
                    Movements movements = new Movements();

                    movements.setId(publish.getId().toHexString());
                    movements.setImageContent(publish.getMedias().toArray(new String[]{}));
                    movements.setTextContent(publish.getText());
                    movements.setUserId(publish.getUserId());
                    movements.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

                    //从userInfo里面填充数据
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));
                    movements.setCommentCount(10); //TODO 评论数
                    movements.setDistance("1.2公里"); //TODO 距离

                    String likeCommentKey = "QUANZI_COMMENT_LIKE_" + movements.getId();
                    if(this.redisTemplate.hasKey(likeCommentKey)){
                        String s = this.redisTemplate.opsForValue().get(likeCommentKey);
                        movements.setLikeCount(Integer.valueOf(s));
                    } else {
                        movements.setLikeCount(0);
                    }

                    // 记录当前用于已经点赞
                    String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
                    if(this.redisTemplate.hasKey(likeUserCommentKey)) {
                        movements.setHasLiked(1);
                    } else {
                        movements.setHasLiked(0);
                    }

                    String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
                    if(this.redisTemplate.hasKey(loveCommentKey)) {
                        movements.setLoveCount(Integer.valueOf(this.redisTemplate.opsForValue().get(loveCommentKey)));
                    }else {
                        movements.setLoveCount(0);
                    }


                    // 记录当前用于已经喜欢
                    String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
                    if(this.redisTemplate.hasKey(loveUserCommentKey)) {
                        movements.setHasLoved(1);
                    } else {
                        movements.setHasLoved(0);
                    }

                    list.add(movements);
                    break;

                }
            }


        }
        return list;
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return getPageResult(page, pageSize, null);
    }


    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean b = this.quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!b) {
            return null;
        }

        // 保存成功，获取点赞数
        Long likeCount = 0L;
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        //如果有这个key就自增
        if(this.redisTemplate.hasKey(likeCommentKey)){
            likeCount = this.redisTemplate.opsForValue().increment(likeCommentKey);
        } else {
            //没有这个key，默认设置1
            likeCount=1L;
            this.redisTemplate.opsForValue().set(likeCommentKey, "1");
        }

        // 记录当前用于已经点赞
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey, "1");
        return likeCount;
    }

    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean b = this.quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!b) {
            return null;
        }

        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long decrement = this.redisTemplate.opsForValue().decrement(likeCommentKey);

        // 记录当前用于已经点赞
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommentKey);

        return decrement;
    }

    /**
     * 喜欢
     * @param publishId
     * @return
     */
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean bool = this.quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!bool) {
            //保存失败
            return null;
        }

        // 保存成功，获取喜欢数
        Long loveCount = 0L;
        String likeCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        if (!this.redisTemplate.hasKey(likeCommentKey)) {
            Long count = this.quanZiApi.queryCommentCount(publishId, 3);
            loveCount = count;
            this.redisTemplate.opsForValue().set(likeCommentKey, String.valueOf(loveCount));
        } else {
            loveCount = this.redisTemplate.opsForValue().increment(likeCommentKey);
        }

        // 记录当前用于已经喜欢
        String likeUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey, "1");

        return loveCount;
    }

    public Long unLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!bool) {
            return null;
        }

        // redis中的喜欢数需要减少1
        String likeCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommentKey);

        // 删除该用户的标记喜欢
        String likeUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommentKey);

        return count;
    }

    public Movements queryMovementsById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);

        List<Publish> list = new ArrayList<>();
        list.add(publish);
        List<Movements> movements = getMovements(list);
        return movements.get(0);

    }

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;


    public List<VisitorsVo> queryVisitorsList() {
        //首先查看redis里面有没设置上次访客时间
        Long userId = UserThreadLocal.get().getId();
        String redisKey = "VISITORS_" + userId;
        List<Visitors> visitors;
        String v = this.redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isNotEmpty(v)) {
            visitors = visitorsApi.topVisitor(userId, Long.valueOf(v));
        } else {
            visitors = visitorsApi.topVisitor(userId, 6);
        }

        Set<Long> userIDs = visitors.stream().map(Visitors::getVisitorUserId).collect(Collectors.toSet());
        if (userIDs.size() == 0) {
            return Collections.emptyList();
        }
        //去数据库获取userInfo信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIDs);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            for (Visitors visitor : visitors) {
                if (visitor.getVisitorUserId().longValue()==userInfo.getUserId().longValue()) {

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        //更新时间
        this.redisTemplate.opsForValue().set(redisKey, String.valueOf(System.currentTimeMillis()) );

        return visitorsVoList;

    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        List<Publish> records = this.quanZiApi.queryAlbumList(userId, page, pageSize);

        if(CollectionUtils.isEmpty(records)){
            return pageResult;
        }

        pageResult.setItems(this.getMovements(records));

        return pageResult;
    }
}
